package services

import (
	"errors"
	"fmt"
	"im/app/conf"
	"im/app/models"
	"im/app/models/form/user"
	"im/app/util"
	"time"
)

type UserService struct {

}

/**
	@op 登录操作
 	@pamras username string 账户
    @pamras paswowrd string 密码
 */
func (us *UserService) Login(username string, password string) (interface{}, error) {
	user := models.User{}
	err := conf.Mdb.Where("name=?", username).Where("password=?",util.Md5String(password)).First(&user).Error
	if err != nil {
		return nil, errors.New("查询操作错误，数据不存在")
	}
	if user.ID > 0 {
		resultToken, _:= models.JwtGenerateToken(&user,12*3600 * time.Second)  // 12小时
		return resultToken, nil
	}

	return nil, errors.New("数据不存在")
}

func (us *UserService) Register(inputs *user.UserRegister) error {
	user := models.User{}
	conf.Mdb.Where("name=?",inputs.Name).First(&user)
	if user.ID > 0 {
		return errors.New("账号已存在,不能重复注册")
	}
	fmt.Println(user)
	user.Name = inputs.Name
	user.Password = util.Md5String(inputs.Password)
	user.Sex = inputs.Sex
	user.CreatedAt = time.Now().Unix()
	user.UpdatedAt = time.Now().Unix()
	err := conf.Mdb.Create(&user).Error
	if err != nil {
		return errors.New("数据插入失败")
	}

	return nil
}
